package com.sugon.cloudgateway.route;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import com.sugon.cloudgateway.service.RouteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.concurrent.Executor;

@Component
public class RouteServiceImplByNacos implements CommandLineRunner {
    @Autowired
    private RouteService routeService;
    @Autowired
    private NacosGatewayProperties nacosGatewayProperties;
    /**
     * 监听Nacos Server下发的动态路由配置
     */
    public void routeByNacosListener (){
        try {
            //创建ConfigService对象
            ConfigService configService= NacosFactory.createConfigService(nacosGatewayProperties.getAddress());
            //通过ConfigService对Nacos Server上的配置进行操作，比如拉取配置、修改配置等
            //程序启动时从配置中心读取路由配置
            String content = configService.getConfig(nacosGatewayProperties.getDataId(), nacosGatewayProperties.getGroupId(), nacosGatewayProperties.getTimeout());
            System.out.println(content);
            //转成json
            List<RouteDefinition> list = JSON.parseArray(content,RouteDefinition.class);
            if(!CollectionUtils.isEmpty(list)){
                list.forEach( definition->{
                    routeService.update(definition);
                });
            }
            System.out.println("*******************开始监听***************************");
            configService.addListener(nacosGatewayProperties.getDataId(), nacosGatewayProperties.getGroupId(), new Listener() {
                @Override
                public void receiveConfigInfo(String configInfo) {
                    System.out.println(configInfo);
                    List<RouteDefinition> list = JSONUtil.toList(configInfo, RouteDefinition.class);
                    list.forEach( definition->{
                        routeService.update(definition);
                    });
                }
                @Override
                public Executor getExecutor() {
                    return null;
                }
            });
        } catch (NacosException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void run(String... args) throws Exception {
        routeByNacosListener();
    }
}
